from gui import Gui
from config import Config
from preset import Preset

class Preferences(Gui):

    def __init__(self):
        '''
        Displaying the preferences dialog, populate config value into it,
        and save changes done to the configs
        '''
        Gui.__init__(self, 'config', 'preferences_dialog', {
            'on_pref_cancel_button_released' : self.quit,
            'on_pref_close_button_released' : self._pref_close_button_released
        })
        
        self.connect(self.window, 'delete-event', self.quit)
        self.connect(self.window, 'response', self.quit)
        
        from subprocess import Popen, PIPE
        self.options = {
            'tvcard' : [o.rstrip('\n') for o in Popen('ls /dev/video*', shell=True, stdout=PIPE).stdout.readlines()],
            'quality' : ['High', 'Medium'],
            'screen' : ['320x240', '640x480', '1024x768'],
            'video' : ['xv', 'x11', 'gl']
        }
        self.conf = Config()
        self.preset = Preset()
    
        if not hasattr(self, 'populated'):
            self._populate()
        
        self.window.run()
    
    def quit(self, widget, *response):
        '''closing preferences-dialog'''
        self.window.hide()
        return True
    
    def _pref_close_button_released(self, widget):
        '''click on close button and save all settings'''
        self.conf.set_conf('tv_card', self.widget('tvcard_combo').get_model().get_value(self.widget('tvcard_combo').get_active_iter(), 0))
        self.conf.set_conf('tv_opts', self.widget('tv_opts_entry').get_text())
        self.conf.set_conf('autostart', ('1' if self.widget('autostart_button').get_active() else '0'))
        self.conf.set_conf('output_folder', self.widget('output_folder_button').get_filenames()[0])
        self.conf.set_conf('video_codec', self.widget('video_codec_combo').get_model().get_value(self.widget('video_codec_combo').get_active_iter(), 0))
        self.conf.set_conf('audio_codec', self.widget('audio_codec_combo').get_model().get_value(self.widget('audio_codec_combo').get_active_iter(), 0))
        self.conf.set_conf('quality', self.widget('quality_combo').get_model().get_value(self.widget('quality_combo').get_active_iter(), 0).lower())
        self.conf.set_conf('video_out', self.widget('video_out_combo').get_model().get_value(self.widget('video_out_combo').get_active_iter(), 0))
        self.conf.set_conf('cache', (self.widget('cache_spinbutton').get_value_as_int()*1024))
        
        self.conf.save()
        self.quit(widget)
    
    def _populate(self):
        '''
        extract config values from *.conf and
        adjust into dialog
        '''
        import os
        import sys
        import gobject
        try:
            import gtk
        except:
            sys.exit(1)
        c = gtk.CellRendererText()
                
        # tvcard_combo
        tvcard = {
            'combo' : self.widget('tvcard_combo'),
            'store' : gtk.ListStore(gobject.TYPE_STRING),
            'index' : -1
        }
        tvcard['combo'].pack_start(c, True)
        tvcard['combo'].add_attribute(c, 'text', 0)
        for t in self.options['tvcard']:
            t = t.rstrip('\n')
            tvcard['store'].append([t])
            if self.conf.get_conf('tv_card') == t:
                tvcard['index'] = len(tvcard['store'])-1
        tvcard['combo'].set_model(tvcard['store'])
        tvcard['combo'].set_active(tvcard['index'])
    
        # mplayer_opts
        tvopts = self.widget('tv_opts_entry')
        tvopts.set_text(self.conf.get_conf('tv_opts'))
    
        # autostart_tv
        autostart = self.widget('autostart_button')
        autostart.set_active(int(self.conf.get_conf('autostart')))
    
        # output_folder
        output = self.widget('output_folder_button')
        output.set_action(gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER)
        f = os.environ['HOME'] if self.conf.get_conf('output_folder') == '' else self.conf.get_conf('output_folder')
        output.set_current_folder(f)
    
        # video_codec
        vcodec = {
            'combo' : self.widget('video_codec_combo'),
            'store' : gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING),
            'index' : -1
        }
        vcodec['combo'].pack_start(c, True)
        vcodec['combo'].add_attribute(c, 'text', 1)
        for t in self.preset.get_conf('vcodec'):
            vcodec['store'].append([t, self.preset.get_conf('vcodec')[t]])
            if self.conf.get_conf('video_codec') == t:
                vcodec['index'] = len(vcodec['store'])-1
        vcodec['combo'].set_model(vcodec['store'])
        vcodec['combo'].set_active(vcodec['index'])
    
        # audio_codec
        acodec = {
            'combo' : self.widget('audio_codec_combo'),
            'store' : gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING),
            'index' : -1
        }
        acodec['combo'].pack_start(c, True)
        acodec['combo'].add_attribute(c, 'text', 1)
        for t in self.preset.get_conf('acodec'):
            acodec['store'].append([t, self.preset.get_conf('acodec')[t]])
            if self.conf.get_conf('audio_codec') == t:
                acodec['index'] = len(acodec['store'])-1
        acodec['combo'].set_model(acodec['store'])
        acodec['combo'].set_active(acodec['index'])
    
        # record_quality
        quality = {
            'combo' : self.widget('quality_combo'),
            'store' : gtk.ListStore(gobject.TYPE_STRING),
            'index' : -1
        }
        quality['combo'].pack_start(c, True)
        quality['combo'].add_attribute(c, 'text', 0)
        for t in self.options['quality']:
            quality['store'].append([t])
            if self.conf.get_conf('quality') == t.lower():
                quality['index'] = len(quality['store'])-1
        quality['combo'].set_model(quality['store'])
        quality['combo'].set_active(quality['index'])
                
        # video_out (vo)
        video = {
            'combo' : self.widget('video_out_combo'),
            'store' : gtk.ListStore(gobject.TYPE_STRING),
            'index' : -1
        }
        video['combo'].pack_start(c, True)
        video['combo'].add_attribute(c, 'text', 0)
        for t in self.options['video']:
            video['store'].append([t])
            if self.conf.get_conf('video_out') == t:
                video['index'] = len(video['store'])-1
        video['combo'].set_model(video['store'])
        video['combo'].set_active(video['index'])
        
        # cache
        cache = self.widget('cache_spinbutton')
        cache.set_value(int(self.conf.get_conf('cache'))/1024)
        
        self.populated = True       
        
